package com.lly.songhigh.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.lly.songhigh.R;
import com.lly.songhigh.adapter.DownloadListViewAdapter;
import com.lly.songhigh.adapter.SongSheetDetailRecyclerAdapter;
import com.lly.songhigh.application.BaseApplication;
import com.lly.songhigh.constant.StringResouce;
import com.lly.songhigh.constant.URL;
import com.lly.songhigh.entity.dao.RecentPlay;
import com.lly.songhigh.service.DownloadServices;
import com.lly.songhigh.entity.MusicInfo;
import com.lly.songhigh.entity.SongSheetDetail;
import com.lly.songhigh.entity.dao.AddTo;
import com.lly.songhigh.entity.dao.Collection;
import com.lly.songhigh.eventbus.MyEvent;
import com.lly.songhigh.greendao.DaoSingleton;
import com.lly.songhigh.utils.ChangeUtils;
import com.lly.songhigh.view.PublishSelectPicPopupWindow;
import com.lly.songhigh.volley.StringRequestUtf;
import com.lly.songhigh.volley.VolleySingleton;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.media.SinaShareContent;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import it.sephiroth.android.library.picasso.Picasso;

/**
 * Created by dllo on 15/10/23.
 */

public class SongSheetDetailActivity extends BaseActivity implements View.OnClickListener, SongSheetDetailRecyclerAdapter.OnMenuClickListener, SongSheetDetailRecyclerAdapter.OnItemListener {

    private ImageView songListDetailToolbarBack, songListDetailImg;
    private TextView detailDescription, detailListenCount, pw_collection, pw_download, pw_share, pw_singer,
            pw_album, pw_song_info, songSheetShare, detailTitle, songs_list_collection;
    private CollapsingToolbarLayout songListDetailCollapsingToolbar;
    private String url, shareUrl, songSheetShareUrl; // 解析的网址
    private VolleySingleton volleySingleton;
    private SongSheetDetail.ImageEntity imageEntity;
    private List<SongSheetDetail.SongsEntity> songsEntities;
    private RecyclerView songListDetailRecyclerView;
    private SongSheetDetailRecyclerAdapter adapter;
    private PublishSelectPicPopupWindow menuWindow;
    private RelativeLayout alpha_layout;
    private SongSheetDetail.SongsEntity itemSongsEntity;
    private List<MusicInfo> musicInfos;
    private DaoSingleton daoSingleton;
    private ListView downListView;
    private AlertDialog alertDialog;
    private int id;
    UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.share");
    private List<Collection> collections;
    private Context mContext = SongSheetDetailActivity.this;
    private SongSheetDetail songSheetDetail;
    private boolean isCollected; // 标记是否被收藏
    private Toast mToast;
    private String path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_charts_detail);
        BaseApplication.getInstance().addActivity(this);
        initView();
        volleySingleton = VolleySingleton.getInstance();
        songListDetailToolbarBack.setOnClickListener(this);
        initData();
        daoSingleton = DaoSingleton.getInstance();
        initShare();
        QQShare();
        songSheetQQShare();
    }

    private void initView() {
        mToast = Toast.makeText(this, "", Toast.LENGTH_LONG);
        songListDetailImg = (ImageView) findViewById(R.id.charts_detail_img);
        songListDetailToolbarBack = (ImageView) findViewById(R.id.detail_toolbar_back);
        songListDetailCollapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.detail_collapsing_toolbar);
        songListDetailRecyclerView = (RecyclerView) findViewById(R.id.charts_detail_recycler_view);
        detailListenCount = (TextView) findViewById(R.id.detail_listen_count);
        detailDescription = (TextView) findViewById(R.id.detail_description);
        songSheetShare = (TextView) findViewById(R.id.songs_list_share);
        detailTitle = (TextView) findViewById(R.id.detail_title);
        songSheetShare.setOnClickListener(this);
        songs_list_collection = (TextView) findViewById(R.id.songs_list_collection);
        songs_list_collection.setOnClickListener(this);

        // 设置列表布局的方向, 通过布局管理器对象
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        songListDetailRecyclerView.setLayoutManager(layoutManager);
        alpha_layout = (RelativeLayout) findViewById(R.id.alpha_layout);
        songListDetailCollapsingToolbar.setExpandedTitleTextAppearance(R.style.CollapsingToolbarLayoutText);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isCollected = daoSingleton.getAddToById(id) != null && daoSingleton.getAddToById(id).size() > 0;
        if (isCollected)
            songs_list_collection.setText(StringResouce.CANCEL_COLLECTION);
        else
            songs_list_collection.setText(StringResouce.COLLECTION);
    }

    private void initData() {
        musicInfos = new ArrayList<>();
        Intent intent = getIntent();
        id = intent.getIntExtra("id", 0);
        url = URL.SONG_SHEET_DETAIL_START_URL + id + URL.SONG_SHEET_DETATL_END_URL;
        songSheetShareUrl = "http://quan.dongting.com/do.html?m=music&a=details&id=" + id;
        Log.i("qiqi", "url = " + url);
        StringRequestUtf stringRequestUtf = new StringRequestUtf(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                songSheetDetail = gson.fromJson(response, SongSheetDetail.class);
                songListDetailCollapsingToolbar.setTitle(songSheetDetail.getTitle());
                detailTitle.setText(songSheetDetail.getTitle());
                imageEntity = songSheetDetail.getImage();
                Picasso.with(SongSheetDetailActivity.this).load(imageEntity.getPic()).placeholder(R.mipmap.placeholder_detail_radio_ban).error(R.mipmap.placeholder_detail_radio_ban).into(songListDetailImg);
                songsEntities = songSheetDetail.getSongs();
                adapter = new SongSheetDetailRecyclerAdapter(SongSheetDetailActivity.this, songsEntities);
                adapter.setOnMenuClickListener(SongSheetDetailActivity.this);
                adapter.setOnItemListener(SongSheetDetailActivity.this);
                songListDetailRecyclerView.setAdapter(adapter);
                detailDescription.setText(songSheetDetail.getDesc());
                String num = ChangeUtils.getCount(songSheetDetail.getListen_count());
                detailListenCount.setText(num);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        volleySingleton.addQueue(stringRequestUtf);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.detail_toolbar_back:
                finish();
                break;
            case R.id.songs_list_share:
                mController.getConfig().removePlatform(SHARE_MEDIA.RENREN, SHARE_MEDIA.DOUBAN);
                //是否只有已登录用户才能打开分享选择页
                mController.openShare(SongSheetDetailActivity.this, false);
                songSheetQQShare();

                break;
            case R.id.songs_list_collection:
                if (!isCollected) {
                    AddTo addTo = new AddTo(songSheetDetail.getTitle(), songSheetDetail.getImage().getPic(),
                            StringResouce.SONGSHEET, songSheetDetail.getSongs().size(), songSheetDetail.getSonglist_id());
                    daoSingleton.getAddToDao().insert(addTo);
                    songs_list_collection.setText(StringResouce.CANCEL_COLLECTION);
                    isCollected = true;
                    mToast.setText(StringResouce.COLLECTION_SUCCESS);
                    mToast.show();
                } else {
                    daoSingleton.deleteAddToById(id);
                    songs_list_collection.setText(StringResouce.COLLECTION);
                    isCollected = false;
                    mToast.setText(StringResouce.CANCEL_COLLECTION_SUCCESS);
                    mToast.show();
                }
                break;
        }
    }

    private void songSheetQQShare() {
        QQShareContent qqShareContent = new QQShareContent();
        qqShareContent.setShareContent(StringResouce.SHARE_CONTENT);
        qqShareContent.setTitle(StringResouce.SHARE_TITLE);
        qqShareContent.setTargetUrl(songSheetShareUrl);
        mController.setShareMedia(qqShareContent);
        QZoneShareContent qzone = new QZoneShareContent();
        //设置分享文字
        qzone.setShareContent(StringResouce.SHARE_CONTENT);
        //设置分享内容的标题
        qzone.setTitle(StringResouce.SHARE_TITLE);
        //设置点击消息的跳转URL
        qzone.setTargetUrl(songSheetShareUrl);
        mController.setShareMedia(qzone);

        SinaShareContent shareContent = new SinaShareContent();
        shareContent.setTitle(StringResouce.SHARE_TITLE);
        shareContent.setShareContent(StringResouce.SHARE_CONTENT + shareUrl);
        mController.setShareMedia(shareContent);
    }

    @Override
    public void onMenuClick(SongSheetDetail.SongsEntity songsEntity) {
        View view = LayoutInflater.from(this).inflate(R.layout.popup_window, null);
        itemSongsEntity = songsEntity;
        if (songsEntity.getUrlList().size() > 0) {
            shareUrl = URL.SHARE_SINGLE_START + songsEntity.getSongId() + URL.SHARE_SINGLE_END;
        }
        pw_collection = (TextView) view.findViewById(R.id.pw_collection);
        pw_download = (TextView) view.findViewById(R.id.pw_download);
        pw_share = (TextView) view.findViewById(R.id.pw_share);
        pw_singer = (TextView) view.findViewById(R.id.pw_singer);
        pw_album = (TextView) view.findViewById(R.id.pw_album);
        pw_song_info = (TextView) view.findViewById(R.id.pw_song_info);
        pw_song_info.setText(StringResouce.SONGNAME + songsEntity.getName());
        pw_singer.setText(StringResouce.SINGERNAME + songsEntity.getSingerName());
        if (songsEntity.getAlbumName() != null && !songsEntity.getAlbumName().equals("")) {
            pw_album.setText(StringResouce.ALBUMNAME + songsEntity.getAlbumName());
        }
        menuWindow = new PublishSelectPicPopupWindow(this, itemsOnClick, view, alpha_layout);
        menuWindow.showAtLocation(findViewById(R.id.detail_toolbar),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        alpha_layout.setVisibility(View.VISIBLE);
        collections = daoSingleton.getCollectionById((int) songsEntity.getSongId());
        if (collections.size() > 0 && collections != null)
            pw_collection.setText(StringResouce.CANCEL_COLLECTION);
        else
            pw_collection.setText(StringResouce.COLLECTION);
    }

    @Override
    public void onItemClick(SongSheetDetail.SongsEntity songsEntity, int position) {
        if (songsEntity.getUrlList() != null && songsEntity.getUrlList().size() > 0) {
            Intent intent = new Intent(SongSheetDetailActivity.this, PlayMusicActivity.class);
            daoSingleton.getRecentPlayDao().insertOrReplace(new RecentPlay(songsEntity.getName(),
                    songsEntity.getSingerName(), songsEntity.getAlbumName(),
                    StringResouce.RESOUCE_NET, songsEntity.getUrlList().get(0).getUrl(),
                    (long)songsEntity.getAlbumId(), (long)songsEntity.getUrlList().get(0).getDuration(),
                    (long)songsEntity.getSongId()));
            musicInfos = new ArrayList<>();
            for (SongSheetDetail.SongsEntity entity : songsEntities) {
                if (entity.getUrlList() != null && entity.getUrlList().size() > 0) {
                    MusicInfo musicInfo = new MusicInfo();
                    musicInfo.setUrl(entity.getUrlList().get(0).getUrl());
                    musicInfo.setDuration(entity.getUrlList().get(0).getDuration());
                    musicInfo.setSingerId(entity.getSingerId());
                    musicInfo.setSingerName(entity.getSingerName());
                    musicInfo.setSongId(entity.getSongId());
                    musicInfo.setSongName(entity.getName());
                    musicInfo.setAlbum(entity.getAlbumName());
                    musicInfo.setAlbumId((long)entity.getAlbumId());
                    musicInfo.setResouce(StringResouce.RESOUCE_NET);
                    musicInfos.add(musicInfo);
                }
            }
            EventBus.getDefault().post(new MyEvent.DeliverData(musicInfos, songsEntity.getName()));
            intent.putParcelableArrayListExtra("musicInfos", (ArrayList<? extends Parcelable>) musicInfos);
            startActivity(intent);
        } else {
            Toast.makeText(SongSheetDetailActivity.this, StringResouce.PLAY_ERROR, Toast.LENGTH_LONG).show();
        }
    }

    // 弹出popupwindow的按钮监听
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        private AlertDialog.Builder builder;

        @Override
        public void onClick(View v) {
            menuWindow.dismiss();
            alpha_layout.setVisibility(View.GONE);
            switch (v.getId()) {
                case R.id.pw_collection:
                    if (!(collections.size() > 0 && collections != null)) {
                        Collection collection = new Collection();
                        collection.setSongName(itemSongsEntity.getName());
                        collection.setDuration((long) itemSongsEntity.getUrlList().get(0).getDuration());
                        collection.setAlbumId((long) itemSongsEntity.getAlbumId());
                        collection.setAlbum(itemSongsEntity.getAlbumName());
                        collection.setPlayUrl(itemSongsEntity.getUrlList().get(0).getUrl());
                        collection.setSingerName(itemSongsEntity.getSingerName());
                        collection.setSongId((long) itemSongsEntity.getSongId());
                        daoSingleton.getCollectionDao().insert(collection);
                        Toast.makeText(SongSheetDetailActivity.this, StringResouce.COLLECTION_SUCCESS, Toast.LENGTH_LONG).show();
                    } else {
                        daoSingleton.deleteCollectionById(itemSongsEntity.getSongId());
                        Toast.makeText(SongSheetDetailActivity.this, StringResouce.DELETE_COLLECTION, Toast.LENGTH_LONG).show();
                    }
                    break;
                case R.id.pw_share:

                    if (itemSongsEntity.getUrlList().size() > 0) {
                        mController.getConfig().removePlatform(SHARE_MEDIA.RENREN, SHARE_MEDIA.DOUBAN);
                        //是否只有已登录用户才能打开分享选择页
                        mController.openShare(SongSheetDetailActivity.this, false);
                        QQShare();

                    } else {
                        Toast.makeText(SongSheetDetailActivity.this, StringResouce.SHARE_ERROR, Toast.LENGTH_LONG).show();
                    }

                    break;
                case R.id.pw_download:
                    if (itemSongsEntity.getAuditionList().size() == 0) {
                        Toast.makeText(SongSheetDetailActivity.this, StringResouce.NO_RESOURCES, Toast.LENGTH_SHORT).show();
                    } else {
//                        EventBus.getDefault().post(new MyEvent.GetFileName(itemSongsEntity.getName()));
                        View view = LayoutInflater.from(SongSheetDetailActivity.this).inflate(R.layout.downloaddialog, null);
                        downListView = (ListView) view.findViewById(R.id.download_listView);
                        DownloadListViewAdapter adapter = new DownloadListViewAdapter(itemSongsEntity.getAuditionList(), SongSheetDetailActivity.this);
                        downListView.setAdapter(adapter);
                        builder = new AlertDialog.Builder(SongSheetDetailActivity.this);
                        builder.setMessage(StringResouce.CHOOSE_QUALITY);
                        builder.setView(view);
                        alertDialog = builder.create();
                        alertDialog.show();
                        downListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                startDownloadService();
                                path = itemSongsEntity.getAuditionList().get(position).getUrl();
                                Toast.makeText(SongSheetDetailActivity.this, StringResouce.START_DOWNLOADING, Toast.LENGTH_SHORT).show();
                                alertDialog.dismiss();
                            }
                        });
                    }

                    break;

                case R.id.pw_singer:
                    Intent intent = new Intent(SongSheetDetailActivity.this, SingerDetailActivity.class);
                    intent.putExtra("singerId", itemSongsEntity.getSingerId());
                    startActivity(intent);
                    break;

                case R.id.pw_album:
                    Intent intentToAlbum = new Intent(SongSheetDetailActivity.this, SearchAlbumDetialsActivity.class);
                    intentToAlbum.putExtra("_url", itemSongsEntity.getAlbumId());
                    startActivity(intentToAlbum);
                    break;
            }
        }
    };

    public void onEventMainThread(MyEvent.IsDlding isDlding) {
        if (isDlding.isDownloading()) {
            EventBus.getDefault().post(new MyEvent.DldMessage(itemSongsEntity.getName(), path));
        }
    }
    public void startDownloadService() {
        Intent i = new Intent(mContext, DownloadServices.class);
        mContext.startService(i);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    private void initShare() {
        UMQQSsoHandler umqqSsoHandler = new UMQQSsoHandler(this, "100424468",
                "c7394704798a158208a74ab60104f0ba");
        umqqSsoHandler.addToSocialSDK();
        QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this, "100424468",
                "c7394704798a158208a74ab60104f0ba");
        qZoneSsoHandler.addToSocialSDK();
    }

    private void QQShare() {
        QQShareContent qqShareContent = new QQShareContent();
        //设置分享文字
        qqShareContent.setShareContent(StringResouce.SHARE_CONTENT);
        //设置分享title
        qqShareContent.setTitle(StringResouce.SHARE_TITLE);
        //设置点击分享内容的跳转连接
        qqShareContent.setTargetUrl(shareUrl);
        //????
        mController.setShareMedia(qqShareContent);
        QZoneShareContent qzone = new QZoneShareContent();
        //设置分享文字
        qzone.setShareContent(StringResouce.SHARE_CONTENT);
        //设置分享内容的标题
        qzone.setTitle(StringResouce.SHARE_TITLE);
        //设置点击消息的跳转URL
        qzone.setTargetUrl(shareUrl);
        mController.setShareMedia(qzone);

        SinaShareContent shareContent = new SinaShareContent();
        shareContent.setTitle(StringResouce.SHARE_TITLE);
        shareContent.setShareContent(StringResouce.SHARE_CONTENT + shareUrl);
        mController.setShareMedia(shareContent);
    }

}
